package code.c03_stackQueue.linkQueue;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/10/7 17:33
 * @package code.c03_stackQueue.linkQueue
 * @description 没有头结点的链队
 */

public class LinkQueueClass <E> {
    LinkNode<E> front;
    LinkNode<E> rear;

    public LinkQueueClass() {
        front = null;
        rear = null;
    }

    // ================== 基本算法 ==================
    public boolean empty(){
        return front == null;
    }

    /**
     * 入栈操作
     * @param e
     */
    public void push(E e){
        LinkNode<E> s = new LinkNode<>(e);
        // 如果原链队为空（没有头结点，front 指向首节点）
        if (empty()){
            front = rear =s;
        }else {
            rear.next =s;
            rear =s;
        }
    }

    /**
     * 出栈操作
     * @return
     */
    public E pop(){
        E e;
        if (empty()){
            throw new IllegalArgumentException("出队：队为空");
        }
        // 如果只有一个结点
        if (front == rear){
            e = front.data;
            front = rear = null;
        }else {
            e = front.data;
            front = front.next;
        }

        return e;
    }

    /**
     * 取队头元素
     * @return
     */
    public E peek(){

        if (empty()){
            throw new IllegalArgumentException("取队头元素：队为空");
        }

        return front.data;
    }
}
